package com.xju.servlet;

import java.io.IOException;
import java.util.Collections;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import com.xju.dao.ClassDao;
import com.xju.dao.ClassDaoImpl;
import com.xju.entity.Class;

@WebServlet("/api/classes")
public class ClassServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private final ClassDao classDao = new ClassDaoImpl();
    private final Gson gson = new Gson();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        // 设置响应头
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        
        // 获取参数并验证
        String majorId = request.getParameter("majorId");
        if (majorId == null || majorId.isEmpty()) {
            sendErrorResponse(response, HttpServletResponse.SC_BAD_REQUEST, "缺少majorId参数");
            return;
        }
        
        try {
            // 查询并返回结果
            List<Class> classes = classDao.findClassesByMajorId(Integer.parseInt(majorId));
            response.getWriter().write(gson.toJson(classes));
        } catch (NumberFormatException e) {
            sendErrorResponse(response, HttpServletResponse.SC_BAD_REQUEST, "majorId参数格式错误");
        } catch (Exception e) {
            sendErrorResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "服务器内部错误: " + e.getMessage());
        }
    }
    
    /**
     * 统一错误响应方法
     */
    private void sendErrorResponse(HttpServletResponse response, int statusCode, String message) 
            throws IOException {
        response.setStatus(statusCode);
        response.getWriter().write(gson.toJson(
            Collections.singletonMap("error", message)
        ));
    }
}